package com.example.demo.aop;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.example.demo.annotation.Verify;

@Aspect
@Order(-1)  // 该切面应当先于 @Transactional 执行
@Component
public class VerifyAspect {
	
	private static final Logger logger = LogManager.getLogger(VerifyAspect.class);

	/**
	 * 接口请求环绕
	 * @apiNote：
	 * 	HttpServletRequest request首位(必须)
	 * 	Map<String, Object> userinfo次位(必须)
	 * **/
	@Around("@annotation(verify))")
	public Object AroundVerify(ProceedingJoinPoint point, Verify verify) throws Throwable{
		/** around before **/
		Object[] args = point.getArgs();
		
		// session 校验
		if(verify.sessionVerify()) {
			HttpServletRequest request = (HttpServletRequest)args[0];
			String username = ">>>>Around1：" + request.getSession().getAttribute("username");
			logger.info(username);
		}
		
		// 载入参数并响应结果
        Object responseObject = point.proceed(args);
        
        // session 校验
 		if(verify.sessionVerify()) {
 			HttpServletRequest request = (HttpServletRequest)args[0];
 			String username = ">>>>Around2：" + request.getSession().getAttribute("username");
 			logger.info(username);
 		}
		
		/** around after **/ 
		return responseObject;
	}
	
	/**
	 * 接口请求前
	 *   **/
	@Before("@annotation(verify))")
    public void BeforeApi(JoinPoint point, Verify verify) {
		Object[] args = point.getArgs();
		// session 校验
		if(verify.sessionVerify()) {
			HttpServletRequest request = (HttpServletRequest)args[0];
			String username = ">>>>Before：" + request.getSession().getAttribute("username");
			logger.info(username);
		}
    }
	
	/**
	 * 接口请求后
	 *   **/
	@After("@annotation(verify))")
	public void AfterApi(JoinPoint point, Verify verify) {
		Object[] args = point.getArgs();
		// session 校验
		if(verify.sessionVerify()) {
			HttpServletRequest request = (HttpServletRequest)args[0];
			String username = ">>>>After：" + request.getSession().getAttribute("username");
			logger.info(username);
		}
	}
}
